package admin

import (
	"sort"

	// "strconv"

	adminModel "github.com/cn-joyconn/goadmin/models/admin"
	// adminServices "github.com/cn-joyconn/goadmin/services/admin"
	global "github.com/cn-joyconn/goadmin/models/global"
	// gologs "github.com/cn-joyconn/gologs"
	// strtool "github.com/cn-joyconn/goutils/strtool"
)

type AdminUserPermissionService struct {
}

/**
* 获取用户的角色列表
*
* @param uid
* @return
 */
func (service *AdminUserPermissionService) GetUserRoles(uid adminModel.Juint64) *[]*adminModel.AdminRole {
	roleids := service.GetUserRoleIDs(uid)
	if roleids != nil && len(*roleids) > 0 {
		adminRoleService := &AdminRoleService{}
		result := adminRoleService.SelectByRoleIds(*roleids)
		return result
	} else {
		return nil
	}
}

/**
* 获取用户的角色列表
*
* @param uid
* @return
 */
func (service *AdminUserPermissionService) GetUserRoleIDs(uid adminModel.Juint64) *[]int {
	if uid < 0 {
		return nil
	}
	// if global.IsSuperAdmin(uid) {
	// 	return this.selectAllRole("", appid,1,Integer.MAX_VALUE);
	// }
	result := make([]int, 0)
	adminUserService := &AdminUserService{}
	userRolesModels := adminUserService.GetUserRolesByUid(uid.ToString())
	if userRolesModels != nil && len(*userRolesModels) > 0 {
		for _, roleLimitTimeModel := range *userRolesModels {
			if roleLimitTimeModel != nil && roleLimitTimeModel.IsEffectiveTime() {
				result = append(result, roleLimitTimeModel.Role)
			}
		}
	}
	return &result
}

// /**
// * 获取用户的权限列表数据
// *
// * @param uid
// * @return
//  */
//  func (service *AdminUserPermissionService) GetUserResourcesList(uid adminModel.Juint64, roleid int) []int {

// 	list := service.GetUserResources(uid, roleid)
// 	return *list
// }
// /**
// * 获取用户的权限列表
// *
// * @param uid
// * @return
//  */
// func (service *AdminUserPermissionService) GetUserResources(userid adminModel.Juint64, roleid int) *[]int {

// 	adminRoleResourceService := &AdminRoleResourceService{}
// 	if global.IsSuperAdmin(uint64(userid)) {
// 		allResource := adminRoleResourceService.SelectByRoleID(roleid)
// 		return allResource
// 	}
// 	roleIDs := service.GetUserRoleIDs(userid)
// 	resourceList := make([]int, 0)
// 	if roleIDs != nil && len(*roleIDs) > 0 {
// 		adminRoleResourceService := &AdminRoleResourceService{}

// 		var resourceIds []int
// 		for _, roleID := range *roleIDs {
// 			if roleID != 0 {
// 				resourceIds = *(adminRoleResourceService.SelectByRoleID(roleID))
// 				if resourceIds != nil {
// 					for _, resourceId := range resourceIds {
// 						resourceList = append(resourceList, resourceId)
// 					}
// 				}
// 			}
// 		}

// 	}
// 	return &resourceList
// }

/**
* 获取用户的权限列表
*
* @param uid
* @return
 */
func (service *AdminUserPermissionService) GetUserResourceIDs(appid int, userid adminModel.Juint64) *[]int {
	// if strtool.IsBlank(userid) {
	// 	return nil
	// }
	// uid, err := strconv.Atoi(userid)
	// if err != nil {
	// 	return nil
	// }
	result := make([]int, 0)
	adminResourceService := &AdminResourceService{}
	if global.IsSuperAdmin(uint64(userid)) {
		resourceList := adminResourceService.SelectAll(appid)
		for _, resourceObj := range *resourceList {
			if resourceObj.PId != 0 {
				result = append(result, resourceObj.PId)
			}
		}
		return &result
	}

	roleIDs := service.GetUserRoleIDs(userid)
	if roleIDs != nil && len(*roleIDs) > 0 {
		adminRoleResourceService := &AdminRoleResourceService{}
		var resourceIds []int
		for _, roleID := range *roleIDs {
			if roleID != 0 {
				resourceIds = *(adminRoleResourceService.SelectByRoleID(roleID))
				if resourceIds != nil {
					for _, resourceId := range resourceIds {
						result = append(result, resourceId)
					}
				}
			}
		}

		return &result

	}
	return nil
}

// func (service *AdminUserPermissionService) GetUserPermissions(appid int,userid adminModel.Juint64) *[]string {
// 	models := service.GetUserResources(appid,userid)
// 	result := make([]string, 0)
// 	if models != nil {

// 		for _, model := range *models {
// 			result = append(result, model.PPermission)
// 		}
// 	}
// 	return &result

// }



/**
* 获取用户的权限列表数据
*
* @param uid
* @return
 */
// func (service *AdminUserPermissionService) GetUserResourcesListForMenu(appid int,uid adminModel.Juint64) []adminModel.AdminResource {
// 	// result :=&adminModel.AdminResource{
// 	// 	PId: 0,
// 	// 	PDesc: "",
// 	// 	PName: "权限管理",
// 	// 	PPid: -1,
// 	// 	PType: 3,
// 	// 	PPermission: "",
// 	// 	PLevel: 0,
// 	// 	Children:make([]*adminModel.AdminResource, 0),
// 	// }
// 	list := service.GetUserResources(appid,uid)

// 	menuResourcesList := make([]adminModel.AdminResource, 0)
// 	for _, adminResourceModel := range *list {
// 		if adminResourceModel.PType > 0 {
// 			menuResourcesList = append(menuResourcesList, adminResourceModel)
// 		}

// 	}
// 	// return list2Tree(result, menuResourcesList);
// 	return menuResourcesList
// }

// func  (service *AdminUserPermissionService)GetUserResourcesTree(list []*adminModel.AdminResource) *adminModel.AdminResource{
// 	result :=&adminModel.AdminResource{
// 		PId: 0,
// 		PDesc: "",
// 		PName: "权限管理",
// 		PPid: -1,
// 		PType: 3,
// 		PPermission: "",
// 		PLevel: 0,
// 		Children:make([]*adminModel.AdminResource, 0),
// 	}
// 	return list2Tree(result, list);
// }

/**
* 获取用户是否具有该路径的访问权限(resource优先)
*
* @param uid
* @param resuorces
* @return
 */
func (service *AdminUserPermissionService) PathPermissin(appid int, userid adminModel.Juint64, resuorces string) bool {
	// if strtool.IsBlank(userid) {
	// 	return false
	// }
	// uid, err := strconv.Atoi(userid)
	// if err != nil {
	// 	return false
	// }
	if global.IsSuperAdmin(uint64(userid)) {
		return true
	}
	if len(resuorces) == 0 {
		return false
	}
	// JoyConnAuthenticatePermissionResourceModel joyConnAuthenticatePermissionResourceModel = null;
	roleIDs := service.GetUserRoleIDs(userid)
	if roleIDs == nil || len(*roleIDs) == 0 {
		return false
	}
	adminResourceService := &AdminResourceService{}
	resourceModel := adminResourceService.SelectBypPermission(appid, resuorces)
	if resourceModel == nil  {
		return true
	}

	adminRoleResourceService := &AdminRoleResourceService{}
	roleResouceCacheObjs := *(adminRoleResourceService.selectByResourceID(resourceModel.PId))

	for _, roleid := range *roleIDs {
		for _, roleResouceCacheObj := range roleResouceCacheObjs {
			if roleResouceCacheObj == roleid {
				return true
			}
		}
	}

	return false
}

/**
* 获取用户是否具有该路径的访问权限（role优先）
*
* @param uid
* @param resuorces
* @return
 */
func (service *AdminUserPermissionService) HasPathPermissin(userid adminModel.Juint64, appid int, resuorces []string) []string {
	permission := make([]string, 0)
	// if userid==nil {
	// 	return permission
	// }
	// uid, err := strconv.Atoi(userid)
	// if err != nil {
	// 	return permission
	// }
	if global.IsSuperAdmin(uint64(userid)) {
		return resuorces
	}
	if resuorces == nil || len(resuorces) == 0 {
		return permission
	}
	roleIDs := service.GetUserRoleIDs(userid)
	if roleIDs == nil || len(*roleIDs) == 0 {
		return permission
	}
	adminResourceService := &AdminResourceService{}
	resourceModels := adminResourceService.SelectByPermissions(appid, resuorces)
	if resourceModels == nil || len(resourceModels) == 0 {
		return permission
	}
	adminRoleResourceService := &AdminRoleResourceService{}
	roleResouceCacheObjs := adminRoleResourceService.SelectByRoleIDs(*roleIDs)

	for _, resource := range resourceModels {
		for _, roleResouceCacheObj := range *roleResouceCacheObjs {
			if roleResouceCacheObj.PResource == resource.PId {
				permission = append(permission, resource.PPermission)
				break
			}
		}
	}
	return permission
}

func (service *AdminUserPermissionService) ListResource2Tree(ResourceList []adminModel.AdminResource) *adminModel.AdminResource {
	mLen := len(ResourceList)
	if mLen == 0 {
		return nil
	}
	sort.Sort(adminModel.AdminResources{ResourceList, func(a, b *adminModel.AdminResource) bool {
		if a.PLevel == b.PLevel {
			if a.PSort == b.PSort {
				return a.PId > b.PId
			} else {
				return a.PSort < b.PSort
			}
		} else {
			return a.PLevel < b.PLevel
		}
	}})

	for a := mLen - 1; a > -1; a-- {
		for b := a - 1; b > -1; b-- {
			if ResourceList[a].PPid == ResourceList[b].PId {
				if ResourceList[b].Children == nil {
					ResourceList[b].Children = make([]*adminModel.AdminResource, 0)
				}
				if len(ResourceList[b].Children) > 0 {
					Contain := ResourceList[b].ContainsChild(&ResourceList[a])
					if !Contain {
						ResourceList[b].Children = append(ResourceList[b].Children, &ResourceList[a])
					}
				} else {
					ResourceList[b].Children = append(ResourceList[b].Children, &ResourceList[a])
				}

			}
		}
	}
	return &ResourceList[0]
}

func (service *AdminUserPermissionService) ListMenu2Tree(menuList []adminModel.AdminMenu) *adminModel.AdminMenu {
	mLen := len(menuList)
	if mLen == 0 {
		return nil
	}
	sort.Sort(adminModel.AdminMenus{menuList, func(a, b *adminModel.AdminMenu) bool {
		if a.PLevel == b.PLevel {
			if a.PSort == b.PSort {
				return a.PId > b.PId
			} else {
				return a.PSort < b.PSort
			}
		} else {
			return a.PLevel < b.PLevel
		}
	}})

	for a := mLen - 1; a > -1; a-- {
		for b := a - 1; b > -1; b-- {
			if menuList[a].PPid == menuList[b].PId {
				if menuList[b].Children == nil {
					menuList[b].Children = make([]*adminModel.AdminMenu, 0)
				}
				if len(menuList[b].Children) > 0 {
					Contain := menuList[b].ContainsChild(&menuList[a])
					if !Contain {
						menuList[b].Children = append(menuList[b].Children, &menuList[a])
					}
				} else {
					menuList[b].Children = append(menuList[b].Children, &menuList[a])
				}

			}
		}
	}
	return &menuList[0]
}
func (service *AdminUserPermissionService) removeEmptyNode(model adminModel.AdminMenu) {
	if model.Children != nil && len(model.Children) > 0 {
		var childModel adminModel.AdminMenu
		var length = len(model.Children)
		for i := 0; i < length; {
			childModel = *model.Children[i]
			if childModel.PType == 2 {
				service.removeEmptyNode(childModel)
			}
			if childModel.PType == 3 || (childModel.Children != nil && len(childModel.Children) > 0) {
				i++
			} else {
				model.Children = append(model.Children[:i], model.Children[i+1:]...)
			}
		}

	}
}
